(use-modules
 (srfi srfi-9) ;record tipes
 (srfi srfi-1) ;manipular listas
 (ice-9 q)
; (srfi srfi-18)
 )

(load "scpf.scm")

(define resource
  (make-q))

(define res-m (make-mutex))

(define max-q-size 100)
(define q-size 0)

(define inc-q-size!
  (lambda ()
    (set! q-size (+ q-size 1))))

(define dec-q-size!
  (lambda ()
    (set! q-size (- q-size 1))))

(define produce
;coloca na fila um elemento; por conveniencia; o tamanho atual dela
  (letrec ((produce-aux
	    (lambda ()
	      (mutex-lock! res-m)
	      (if 
	       (< q-size  max-q-size)
	       (begin
;		 (display "produced")(newline)
		 (enq! resource q-size)
		 (inc-q-size!)))
	      (mutex-unlock! res-m))))
    produce-aux))

(define consume
  (lambda ()
    (mutex-lock! res-m)
    (if
     (> q-size 0)
     (display (deq! resource)))
    (mutex-unlock! res-m)))     

(define cons-thr
  (make-thread
   (letrec ((consume-loop (lambda ()
			    (consume)
			    (consume-loop))))
     consume-loop)
   'consumidor))

(define prod-thr
  (make-thread
   (letrec ((produce-loop (lambda ()
			    (produce)
			    (produce-loop))))
     produce-loop)
   'produtor))

(thread-start! cons-thr)
(thread-start! prod-thr)
(thread-join! cons-thr)
(thread-join! prod-thr)


(display "main thread is") (display (current-thread)) (newline)

(report-log)